//
//  WBRefreshControl.swift
//  WeoboWithSteveLi
//
//  Created by SteveLi on 2017/10/19.
//  Copyright © 2017年 李军桦. All rights reserved.
//

import UIKit
///下拉刷新控件偏移量
let WBRefreshControlOffSet: CGFloat = -60
///自定义刷新控件 -- 负责刷新逻辑
class WBRefreshControl: UIRefreshControl {
    //MARK: --重新系统方法
    override func endRefreshing() {
        super.endRefreshing()
        //停止动画
        refreshView.startAnimation()
    }
    //主动触发开始刷新动画 --不会触发监听方法
   override func beginRefreshing() {
        super.beginRefreshing()
        refreshView.startAnimation()
    }
    //MARK： -- KVO 监听方法
    /*
         1.始终待在屏幕上
         2.下拉的时候, frame 的 y 一直变小,相反(向上推)一直变大
         3.默认的 y 是 0
     */
    ///箭头旋转标记
    var rotateFlag = false
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if frame.origin.y > 0 {
            return
        }
        //判断是否正在刷新
        if isRefreshing {
            refreshView.startAnimation()
            return
        }
        if frame.origin.y < WBRefreshControlOffSet && !refreshView.rotateFlag {
            print("反过来")
            refreshView.rotateFlag = true
        }else if  frame.origin.y >= WBRefreshControlOffSet && refreshView.rotateFlag {
            print("转过去")
            refreshView.rotateFlag = false
        }
    }
    
    //MARK: -- 构造函数
    override init() {
        super.init()
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setupUI()
    }
    
    fileprivate func setupUI(){
        //隐藏转轮
        tintColor = UIColor.clear
        //添加控件
        addSubview(refreshView)
        //自动布局 - 从xib加载的控件需要指定大小约束
        refreshView.snp.makeConstraints { (make) in
            make.center.equalTo(self.snp.center)
            make.size.equalTo(refreshView.bounds.size)
        }
        //使用 KVO 监听位置变化 --主队列,当主线程有任务，就不调用队列中的任务执行
        //当前运行循环中所有代码执行完毕后，运行循环结束前开始监听
        //方法触发会在下一次运行循环开始
        DispatchQueue.main.async() {
                  self.addObserver(self, forKeyPath: "frame", options: [], context: nil)
        }
    }
        deinit {
            //删除kvo监听方法
            self.removeObserver(self, forKeyPath: "frame")
    }
    //MARK: ---懒加载控件
    lazy var refreshView = WBRefreshView.refreshView()

}

///刷新视图 --- 负责处理‘动画显示’
class WBRefreshView: UIView {
    //旋转标记
    var rotateFlag = false {
        didSet {
            rotateTipIcon()
        }
    }
    
    @IBOutlet weak var loadingIconView: UIImageView!
    @IBOutlet weak var tipView: UIView!
    @IBOutlet weak var tipIconView: UIImageView!
    
    ///从xib加载 视图
    class func refreshView() ->WBRefreshView {
        //推荐使用 UINib的方式加载XIB
          let nib = UINib(nibName: "WBRefreshView", bundle: nil)
            return nib.instantiate(withOwner: nil, options:nil)[0] as! WBRefreshView
    }
    ///旋转图标动画
    func rotateTipIcon() {
        var angle = CGFloat(Double.pi)
        angle += rotateFlag ?  -0.0000001 : 0.0000001
        UIView.animate(withDuration: 0.5) {
            self.tipIconView.transform = CGAffineTransform.init(rotationAngle: CGFloat(angle))

        }
    }
    ///播放加载动画
     func startAnimation () {
        tipView.isHidden = true
        //判断动画是已经被添加
        let key = "transform.rotation"
        if   loadingIconView.layer.animation(forKey: key) != nil{
            return
        }
        let anim = CABasicAnimation(keyPath: key)
        anim.toValue = 2*Double.pi
        anim.repeatCount = MAXFLOAT
        anim.duration = 0.5
        anim.isRemovedOnCompletion = false
        loadingIconView.layer.add(anim, forKey: key)
    }
    ///停止加载动画
   func stopAnimation() {
        tipView.isHidden = false
        loadingIconView.layer.removeAllAnimations()
    }
}
